# coding:utf-8
import os
import uuid
from captcha.image import ImageCaptcha  # pip install captcha
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import random,string

# 验证码中的字符, 就不用汉字了
# number = ['0','1','2','3','4','5','6','7','8','9']
# alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
# ALPHABET = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
# 验证码一般都无视大小写；验证码长度4个字符
def random_captcha_text(char_set=string.digits+string.ascii_letters, captcha_size=4):
	captcha_text = []
	for i in range(captcha_size):
		c = random.choice(char_set)
		captcha_text.append(c)
	return captcha_text

# 生成字符对应的验证码
def gen_captcha_text_and_image():
	image = ImageCaptcha(width=160, height=60)  # 设置固定尺寸提高清晰度

	captcha_text = random_captcha_text()
	captcha_text = ''.join(captcha_text)

	# 获取脚本所在目录
	script_dir = os.path.dirname(os.path.abspath(__file__))
	# 生成唯一文件名避免冲突
	unique_id = uuid.uuid4().hex[:6]
	filename = f"{captcha_text}_{unique_id}.jpg"
	save_path = os.path.join(script_dir, '../gen_digit/'+filename)

	try:
		image.write(captcha_text, save_path)  # 保存到脚本所在目录
		print(f"验证码已保存: {save_path}")
	except Exception as e:
		print(f"保存失败: {e}")
		return None
	return

if __name__ == '__main__':
	# 测试
	for i in range(10):
		gen_captcha_text_and_image()